package com.handinglian.servicerecord.service.impl;

import com.github.pagehelper.PageHelper;
import com.handinglian.common.dto.CommonPage;
import com.handinglian.common.utils.FastJsonUtil;
import com.handinglian.servicerecord.dto.MessageTemplateDto;
import com.handinglian.servicerecord.entity.MessageTemplate;
import com.handinglian.servicerecord.mapper.MessageTemplateMapper;
import com.handinglian.servicerecord.param.MessageTemplateCreateParam;
import com.handinglian.servicerecord.param.MessageTemplateUpdateParam;
import com.handinglian.servicerecord.service.MessageTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.Future;

@Service
public class MessageTempalateServiceImpl implements MessageTemplateService {

    @Autowired
    private MessageTemplateMapper messageTemplateMapper;

    @Override
    @Transactional
    public int create(MessageTemplateCreateParam createParam, Integer userId) {
        MessageTemplate messageTemplate = FastJsonUtil.ObjectToObject(createParam, MessageTemplate.class);
        messageTemplate.setUserId(userId);
        messageTemplate.setCreateTime(new Date());
        return messageTemplateMapper.insertSelective(messageTemplate);
    }
    @Override
    @Transactional
    public int update(MessageTemplateUpdateParam updateParam) {
        MessageTemplate messageTemplate = FastJsonUtil.ObjectToObject(updateParam, MessageTemplate.class);
        return messageTemplateMapper.updateByPrimaryKeySelective(messageTemplate);
    }

    @Override
    @Transactional
    public int delete(Integer id) {
        return messageTemplateMapper.deleteByPrimaryKey(id);
    }

    @Override
    public MessageTemplateDto get(Integer id) {
        MessageTemplate messageTemplate = messageTemplateMapper.selectByPrimaryKey(id);
        return FastJsonUtil.ObjectToObject(messageTemplate, MessageTemplateDto.class);
    }

    @Override
    public CommonPage<MessageTemplateDto> list(String nameOrContent, String sortField, String sortOrder, Integer pageNum, Integer pageSize) {
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;
        PageHelper.startPage(pageNum, pageSize);
        CommonPage<MessageTemplateDto> messageTemplates = CommonPage.restPage(messageTemplateMapper.list(nameOrContent, sortField, sortOrder));
        return messageTemplates;
    }

    @Override
    @Async
    public Future<Integer> count() {
        return new AsyncResult<>(messageTemplateMapper.count());
    }
}
